package controller

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"strings"

	"kingbloc.util/util"

	"github.com/ant0ine/go-json-rest/rest"
	"github.com/garyburd/redigo/redis"
	"kingbloc.dts/tools"
	"kingbloc.sso/user"
	"log"
	"net/http"
	"strconv"
)

// 所有的 get 请求过滤，分发
func GetDispatcher(rep rest.ResponseWriter, req *rest.Request) {
	var result map[string]string
	result = req.PathParams
	method := result["method"]
	params := req.URL.Query().Get("params")

	fmt.Println(method)
	fmt.Println(params)

	// TODO：发送异步请求日志
	switch strings.ToLower(method) {
	case "myAccount": // 报单
		//MyAccount(rep, req, params)

	default:
		rep.WriteHeader(404)
	}
}

// 所有的 post 请求过滤，分发
func PostDispatcher(rep rest.ResponseWriter, req *rest.Request) {
	var result map[string]string
	bp, err1 := ioutil.ReadAll(req.Body)
	util.CheckErr(err1)

	err2 := json.Unmarshal(bp, &result)
	util.CheckErr(err2)

	method := result["method"]
	params := result["params"]
	fmt.Println(params)

	// TODO：发送异步请求日志

	switch strings.ToLower(method) {

	default:
		rep.WriteHeader(404)
	}
}

// 校验用户请求信息
func validateUserInfo(req *http.Request) *user.User {
	tokenObj, _ := req.Cookie("SSOTOKEN")
	if tokenObj == nil {
		return nil
	}
	token := tokenObj.Value

	if token == "" {
		return nil
	}
	conf := tool.GetConfig()

	redisHost := conf.Get("redis", "host")
	redisPort := conf.Get("redis", "port")
	redisDB, _ := strconv.Atoi(conf.Get("redis", "db"))

	pc := util.GetRedisConn(redisHost+":"+redisPort, redisDB)
	if pc == nil {
		//fmt.Println("error connection to database")
		log.Fatal("error connection to redis")
	}

	ref, _ := redis.String(pc.Do("GET", token))
	userA := new(user.User)

	if ref == "" {
		return nil
	} else {
		json.Unmarshal([]byte(ref), &userA)

	}

	if userA.Id > 0 {
		return userA
	}

	userA = tool.UserByToken(token)
	//my user info
	if userA == nil {
		return nil
	}
	if userA.Id == 0 {
		return nil
	}

	return userA
}
